﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace IronSharePoint.Web.WebControls
{
    public class IronControl : CompositeControl
    {
        public string FeatureId { get; set; }
        public string ScriptPath { get; set; }

        protected IronScriptEngine engine;

        protected override void OnInit(EventArgs e)
        {
            engine = new IronScriptEngine();

            engine.ScriptResolver.FeatureId = new Guid(FeatureId);
            engine.CompileScriptFrom(ScriptPath);

            engine.Scope.SetVariable("this", this);

            if (engine.Scope.ContainsVariable("OnInit"))
            {
                object method = engine.Scope.GetVariable("OnInit");
                engine.Operations.Call(method, e);
            }

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (engine.Scope.ContainsVariable("OnLoad"))
            {
                object method = engine.Scope.GetVariable("OnLoad");
                engine.Operations.Call(method, e);
            }

            base.OnLoad(e);
        }

        protected override void CreateChildControls()
        {
            if (engine.Scope.ContainsVariable("CreateChildControls"))
            {
                object method = engine.Scope.GetVariable("CreateChildControls");
                engine.Operations.Call(method);
            }

            base.CreateChildControls();
        }


        protected override void OnPreRender(EventArgs e)
        {
            if (engine.Scope.ContainsVariable("OnPreRender"))
            {
                object method = engine.Scope.GetVariable("OnPreRender");
                engine.Operations.Call(method, e);
            }

            base.OnPreRender(e);
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if (engine.Scope.ContainsVariable("Render"))
            {
                object method = engine.Scope.GetVariable("Render");
                engine.Operations.Call(method, writer);
            }
            else
                base.Render(writer);
        }

        protected override void OnUnload(EventArgs e)
        {
            if (engine.Scope.ContainsVariable("OnUnload"))
            {
                object method = engine.Scope.GetVariable("OnUnload");
                engine.Operations.Call(method, e);
            }

            base.OnUnload(e);
        }
    }
}
